<?php namespace App\Services;
/**
 * 基础类
 *
 * 基础类Service
 *
 * @author    zhouchao <zhouchao@yunys.com.cn>
 * @copyright 2016 QuanZhouYunYiShang Inc.
 */
use DB;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Lang;
use Validator;
abstract class BaseService{
    protected $table = '';
    protected $where = array();
    protected $select = array();
    protected $whereIn = array();
    protected $order = 'updated_at';
    protected $sort = 'desc';
    protected $locale = '';
    protected $APP_CN_NAMES = array('carousels'=>'轮播图模块','users'=>'设计师','products'=>'产品模块','types'=>'主题模块','brands'=>'品牌商','source_pics'=>'素材','product_temps'=>'模板','collections'=>'作品集','favorites'=>'收藏','announcements'=>'公告');
    protected $App_NAMES = array('carousels'=>1,'users'=>2,'products'=>3,'types'=>4,'brands'=>5,'source_pics'=>6,'product_temps'=>7,'collections'=>8,'favorites'=>9,'announcements'=>10);
    protected $APP_IDS = array(1=>'carousels',2=>'users',3=>'products',4=>'types',5=>'brands',6=>'source_pics',7=>'product_temps',8=>'collections',9=>'favorites',10=>'announcements');
    public function __construct()
    {
    }

    public function getAll(){
        if(!empty($this->select)){
            return DB::table($this->table)
                ->where($this->where)
                ->select($this->select)
                ->orderBy($this->order,$this->sort)
                ->get();
        }else{
            return DB::table($this->table)
                ->where($this->where)
                ->orderBy($this->order,$this->sort)
                ->get();
        }
    }

    public function getAllByResourceIds($resource){
        return DB::table($this->table)
            ->where($this->where)
            ->whereIn($resource,$this->whereIn)
            ->select($this->select)
            ->orderBy($this->order,$this->sort)
            ->get();
    }

    public function getAllNotInResourceIds($resource){
        return DB::table($this->table)
            ->where($this->where)
            ->whereNotIn($resource,$this->whereIn)
            ->select($this->select)
            ->orderBy($this->order,$this->sort)
            ->get();
    }

    public function getAllByResourceIdsPaginated($resource,$count){
        return DB::table($this->table)
            ->where($this->where)
            ->whereIn($resource,$this->whereIn)
            ->select($this->select)
            ->orderBy($this->order,$this->sort)
            ->paginate($count);
    }

    public function getAllPaginated($count){
        if(!empty($this->select)){
            return DB::table($this->table)
                ->where($this->where)
                ->select($this->select)
                ->orderBy($this->order,$this->sort)
                ->paginate($count);
        }else{
            return DB::table($this->table)
                ->where($this->where)
                ->orderBy($this->order,$this->sort)
                ->paginate($count);
        }
    }

    public function pluck($pluck){
        return DB::table($this->table)->where($this->where)->orderBy($this->order,$this->sort)->pluck($pluck);
    }

    public function getById()
    {
        return DB::table($this->table)->where($this->where)->select($this->select)->first();
    }

    public function count(){
        return DB::table($this->table)->where($this->where)->count();
    }

    public function delete()
    {
        return DB::table($this->table)->where($this->where)->delete();
    }

    public function save($data)
    {
        return DB::table($this->table)->insert($data);
    }

    public function update($data){
        return DB::table($this->table)->where($this->where)->update($data);
    }

    /**
     * 设置参数
     * @param $input
     */
    public function setParameter($input){
        $this->table = $input['table'];
        if(isset($input['where'])){
            $this->where = $input['where'];
        }
        if(isset($input['select'])){
            $this->select = $input['select'];
        }
        if(isset($input['whereIn'])){
            $this->whereIn = $input['whereIn'];
        }
        if(isset($input['order'])){
            $this->order = $input['order'];
        }
        if(isset($input['sort'])){
            $this->sort = $input['sort'];
        }
    }

    /**
     * 获取资源ID组（数据库一一对应）
     * @param $per_page
     * @return array
     */
    public function getListByModuleId($per_page){
        $resource_ids = $this->getAllPaginated($per_page)->toArray();
        //$resource_ids = $this->pluck('resource_id')->toArray();
        return array('total_page'=>$resource_ids['last_page'],'per_page'=>$per_page,'current_page'=>$resource_ids['current_page'],'data'=>$resource_ids['data']);
    }

    /**
     * 根据类型ID获取资源ID的集合
     * @param $type_id
     */
    public function getProductListByModuleId($class,$per_page=10){
        $resource_ids = $this->getListByModuleId($per_page);//type_id 集合
        $resources = $class->getListByReSourceIds($resource_ids['data']);
        $resource_ids['data'] = $resources;
        return $resource_ids;
    }

    public function getAppNameByAppid($app_id){
        if(isset($this->APP_IDS[$app_id])){
            return $this->APP_IDS[$app_id];
        }
        return false;
    }

    public function getAppIdByAppName($app_name){
        if(isset($this->App_NAMES[$app_name])){
            return $this->App_NAMES[$app_name];
        }
        return false;
    }

    public function get_app_cn_app_name_by_app_id($app_id){
        $app_name = $this->getAppNameByAppid($app_id);
        if(isset($this->APP_CN_NAMES[$app_name])){
            return $this->APP_CN_NAMES[$app_name];
        }
        return false;
    }

    public function setImagePath($url,$folder = 'images'){
        return env('IMG_URL_STD_PREFIX').$url;
    }

//    protected static function getServiceClassname($classname, $locale = '')
//    {
//        if ($class = $thisfindServiceClassname($classname, $locale)) {
//            return $class;
//        }
//        // fallback to no locale
//        if ($class = $thisfindServiceClassname($classname)) {
//            return $class;
//        }
//        throw new \InvalidArgumentException(sprintf('Unable to find class "%s" with locale "%s"', $classname, $locale));
//    }
//
//    protected static function findServiceClassname($classname, $locale = '')
//    {
//        $class = 'App\\' . ($locale ? sprintf('Services\%s\%s', $locale, $classname) : sprintf('Services\%s', $classname));
//        if (class_exists($class, true)) {
//            return $class;
//        }
//    }

    function getcode($str){
        try{
            $s1 = iconv('UTF-8','GBK//IGNORE',$str);
            //dd($s1);
            $s0 = iconv('GBK','UTF-8//IGNORE',$s1);
            if($s0 == $str){
                return 'utf-8';
            }else{
                return 'gbk';
            }
        }catch(\Exception $e){
            return false;
        }
    }

    public function createResult($state,$result,$lang='globalcodes',$add_message='',$type=1){
        return $type == 1 ? array('message'=>$add_message.Lang::get($lang.'.'.$state),'result'=>$result,'state'=>$state) :
            array('message'=>$add_message,'result'=>$result,'state'=>$state);
    }

    /**
     * Store the incoming blog post.
     *
     * @param  Request  $request
     * @return Response
     */
    public function store(Request $request,$check_data)
    {
        $v = Validator::make($request->all(), $check_data);
        return $v;
    }
}
